<template>
	<u-form ref="form" :model="form" class="_CreateFormContainer" label-width="auto">
		<template v-for="item1 in uiArray">
			<view :key="item1.id" class="formLabel text-xl padding-xs bg-gradual-blue" v-show="item1.label != '' || item1.children.length > 0">{{ item1.label }}</view>
			<template v-if="item1.CtrlType && item1.CtrlType == 'Dtl'">
				<create-dtl-form-container :key="item1.No" :ref="item1.No" :datasource="item1" :flow="flow" :formdisable="formDisable" />
			</template>
			<template v-else-if="item1.CtrlType && item1.CtrlType == 'Ath'">
				<view :key="item1.OID">
					<view class="padding-xs">
						<button :disabled="formDisable || (item1.ath && item1.ath.IsUpload == '0')" class="cu-btn block line-orange  " @click="uploadClick(item1)">
							<text class="cuIcon-upload"></text>
							上传
						</button>
					</view>

					<view class="fileList">
						<view v-for="imgItem in form[item1.formName]">
							<template v-if="isImg(imgItem.url)">
								<view class="athImgCon" :key="imgItem.url">
									<view class="athImgItem">
										<image @click="previewImg(imgItem.url)" class="athImg" mode="aspectFit" :src="imgItem.url" :key="imgItem.url"></image>
									</view>
									<view class="athImgName" @click="previewImg(imgItem.url)">{{ imgItem.name }}</view>
									<view class="athImgClose">
										<text
											v-if="(!formDisable && item1.ath.DeleteWay == 1) || (item1.ath.DeleteWay == 2 && imgItem.Rec == $store.state.user.userInfo.No)"
											@click="athDelClick(item1, imgItem)"
											class="athImgIcon text-gray cuIcon-close"
										></text>
									</view>
								</view>
							</template>
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="formItemCon">
					<create-form-item
						v-for="item in item1.children"
						:key="item.idx"
						:ref="item.originName"
						:form-item-type="item.formItemType"
						:value="form[item.propName]"
						:prop-name="item.propName"
						:options="item.options"
						:form-disable="formDisable"
						:multi-option="item.multiOptions ? item.multiOptions : []"
						@value-change="handleValueChange"
						@validate-item="handleValidateItem"
					/>
				</view>
			</template>
			<div class="padding-xs"></div>
		</template>
	</u-form>
</template>

<script>
import extrasRules from './extrasRules';
import CreateFormItem from '../create-form-item/create-form-item2.vue';
import { mapActions } from 'vuex';
import { imgReg } from '@/utils/reg.js';
import ServerUrl from '@/config/url.js';
import CreateDtlFormContainer from '../create-dtl-form-container/create-dtl-form-container.vue';
export default {
	components: { CreateFormItem, CreateDtlFormContainer },
	props: {
		datasource: {
			type: Object,
			default: () => {
				return {};
			}
		},
		formDisable: {
			type: Boolean,
			default: false
		},
		flow: {
			type: Object,
			default: () => {
				return {};
			}
		}
	},
	data() {
		return {
			uiArray: [], // formItemType: 1.输入框 2.文本域 3.日期选择 4.时间选择 5.数字 6.下拉 7.开关 8.radio 9.地区选择 10.checkbox
			form: {},
			athArr: [],
			rules: {},
			dtlData: [],
			defRules: {}
		};
	},
	watch: {
		datasource: {
			handler(val, oldVal) {
				console.log('dataSourceChange', val, oldVal);
				if (Object.keys(val).length > 0) {
					this.uiArray = [];
					this.form = {};
					this.athArr = [];
					this.initData();
				}
			},
			deep: true,
			immediate: true
		},
		flow: {
			handler(val, oldVal) {
				if (val.FK_Flow) {
					if (extrasRules[val.FK_Flow]) {
						if (extrasRules[val.FK_Flow].formRules) {
							this.rules = extrasRules[val.FK_Flow].formRules(this);
						}
					}
				}
			},
			deep: true,
			immediate: true
		}
	},
	beforeDestroy() {
		this.uiArray = [];
		this.form = {};
		this.rules = {};
	},
	methods: {
		...mapActions({
			athInit: 'flow/athInit',
			athDownload: 'flow/athDownload',
			getSFTable: 'flow/getSFTable',
			getEnums: 'flow/getEnums',
			athDelete: 'flow/athDelete',
			getSFTableKey: 'flow/getSFTableKey',
			runUrlReturnString: 'flow/runUrlReturnString'
		}),
		async initData() {
			let arr = [];
			let selectObj = {}; // 枚举数组按EnumKey组成的对象
			let defaultValueObj = {}; // 默认值对象
			let athObj = {}; // 附件
			let extObj = {}; // 特殊处理对象
			let uiArray = [];
			let groupLabelArr = []; //表单项分组
			let groupIdCache = {}; //表单项分组key/value暂存
			let outSourceSelectObj = {};
			if (this.datasource.UIBindKey) {
				for (let i = 0; i < this.datasource.UIBindKey.length; i++) {
					let e = this.datasource.UIBindKey[i];
					let sfTableRes = await this.getSFTableKey({
						PKVal: e.No
					});
					console.log('sfTableRes', sfTableRes);
					if (sfTableRes && sfTableRes.SrcType == 5) {
						let optionsRes = await this.runUrlReturnString({
							url: `${ServerUrl}/DataUser/SFTableHandler/${sfTableRes.SelectStatement}`
						});
						console.log('optionsRes', optionsRes);
						if (optionsRes) {
							if (Array.isArray(optionsRes)) {
								outSourceSelectObj[e.No] = optionsRes;
							} else if (optionsRes.data) {
								outSourceSelectObj[e.No] = optionsRes.data;
							}
						}
					}
				}
			}
			try {
				arr = JSON.parse(JSON.stringify(this.datasource.Sys_MapAttr));
				if (this.datasource.Sys_Enum && this.datasource.Sys_Enum.length > 0) {
					this.datasource.Sys_Enum.forEach((e, i) => {
						if (selectObj[e.EnumKey]) {
							selectObj[e.EnumKey].push({
								...e,
								label: e.Lab,
								value: e.IntKey,
								Name: e.Lab,
								No: '' + e.IntKey
							});
						} else {
							selectObj[e.EnumKey] = [
								{
									...e,
									label: e.Lab,
									value: '' + e.IntKey,
									Name: e.Lab,
									No: '' + e.IntKey
								}
							];
						}
					});
				}
				if (this.datasource.MainTable && this.datasource.MainTable.length > 0) {
					defaultValueObj = this.datasource.MainTable[0];
				}
				if (this.datasource.Sys_FrmAttachment && this.datasource.Sys_FrmAttachment.length > 0) {
					this.datasource.Sys_FrmAttachment.forEach((e, i) => {
						athObj[e.MyPK] = e;
					});
				}
				if (this.datasource.Sys_MapExt && this.datasource.Sys_MapExt.length > 0) {
					this.datasource.Sys_MapExt.forEach(e => {
						extObj[e.AttrOfOper] = e;
					});
				}
				if (this.datasource.Sys_GroupField && this.datasource.Sys_GroupField.length > 0) {
					this.datasource.Sys_GroupField.forEach((e, i) => {
						groupIdCache[e.OID] = i;
						if (e.CtrlID) {
							//从表分组单独处理
							if (e.CtrlType == 'Dtl') {
								//从表分组单独处理
								for (let i = 0; i < this.datasource.Sys_MapDtl.length; i++) {
									let item = this.datasource.Sys_MapDtl[i];
									if (e.CtrlID == item.No) {
										groupLabelArr.push({
											id: e.OID,
											label: e.Lab,
											isGroupLabel: true,
											children: [],
											groupTips: '',
											CtrlType: 'Dtl',
											...item
										});
										break;
									}
								}
							} else if (e.CtrlType == 'Ath') {
								console.log('Ath', e);
								let str = e.CtrlID.replace(`${e.FrmID}_`, '');
								let formName = `ath_${str}`;
								let obj = {
									...e,
									ath: athObj[e.CtrlID],
									fileList: [],
									formName
								};
								groupLabelArr.push({
									...obj,
									id: e.OID,
									label: e.Lab,
									isGroupLabel: true,
									children: [],
									groupTips: '',
									CtrlType: 'Ath'
								});
								this.$set(this.form, formName, []);
								this.$set(this.rules, formName, [{
									validator: (rule, value, callback) => {
										let NumOfUpload = athObj[e.CtrlID].NumOfUpload;
										if (NumOfUpload == 0) {
											return callback();
										} else if (NumOfUpload > value.length) {
											return callback(`${e.Lab}请至少上传${NumOfUpload}个文件`);
										} else {
											return callback();
										}
									},
									trigger: 'change'
								}]);
								this.getAthList(obj);
							}
						} else {
							groupLabelArr.push({
								id: e.OID,
								label: e.Lab,
								isGroupLabel: true,
								children: []
							});
						}
					});
					groupLabelArr.push({
						//需要显示却没有分组的表单项
						id: 0,
						label: '',
						isGroupLabel: true,
						children: []
					});
				}
			} catch (error) {
				console.log(error);
				return;
			}
			for (let i = 0; i < arr.length; i++) {
				let mapAttr = arr[i];
				// 外部数据类型
				if (mapAttr.LGType == '0' && mapAttr.MyDataType == '1' && mapAttr.UIContralType == 1) {
					let selectOption = outSourceSelectObj[mapAttr.UIBindKey] || this.datasource[mapAttr.KeyOfEn] || this.datasource[mapAttr.UIBindKey] || [];
					if (selectOption == undefined) {
						if (selectObj[mapAttr.UIBindKey]) {
							selectOption = selectObj[mapAttr.UIBindKey];
						} else {
							selectOption = [];
						}
					}
					let uiName = '';
					let formItemType = 6;
					if (mapAttr.UIContralType == 1) {
						uiName = 'DDL_' + mapAttr.KeyOfEn;
					} else if (mapAttr.UIContralType == 3) {
						uiName = 'RB_' + mapAttr.KeyOfEn;
						formItemType = 8;
					}
					// 特殊处理
					// if (mapAttr.KeyOfEn == 'productOne') {
					// 	formItemType = 13;
					// }
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: formItemType,
							value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
							propName: uiName,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								selectOption
							}
						});
					}
					this.rules[uiName] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, uiName, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// 外键类型
				if (mapAttr.LGType == '2' && mapAttr.MyDataType == '1') {
					if (mapAttr.UIVisible) {
						let selectOption = this.datasource[mapAttr.KeyOfEn] || this.datasource[mapAttr.UIBindKey] || [];
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: 6,
							value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								selectOption
							}
						});
					}
					this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// 文本框、附件
				if (mapAttr.MyDataType == '1') {
					// 附件
					if (mapAttr.UIContralType == '6') {
						continue;
					}
					// 签字板
					if (mapAttr.UIContralType == '8') {
						continue;
					}
					// 评分控件
					if (mapAttr.UIContralType == '101') {
						continue;
					}
					//  地图（划掉） 地区选择器
					if (mapAttr.UIContralType == '4') {
						let uiName = 'smc_' + mapAttr.KeyOfEn;
						let formItemType = 9;
						if (mapAttr.UIVisible) {
							let groupLabelIndex = groupLabelArr.length - 1;
							if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
								groupLabelIndex = groupIdCache[mapAttr.GroupID];
							}
							groupLabelArr[groupLabelIndex].children.push({
								formItemType: formItemType,
								value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
								propName: uiName,
								originName: mapAttr.KeyOfEn,
								idx: i,
								options: {
									...this.createOpeions(mapAttr)
								}
							});
						}
						this.rules[uiName] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
						this.$set(this.form, uiName, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
						continue;
					}
					//图片
					if (mapAttr.UIContralType == '11') {
						let defaultValue = defaultValueObj[mapAttr.KeyOfEn] || (this.datasource.Sys_FrmImg.length > 0 ? this.datasource.Sys_FrmImg[0].ImgURL : '');
						let imgUrls = [];
						if (defaultValue) {
							imgUrls = defaultValue.split(',');
						}
						if (mapAttr.UIVisible) {
							let groupLabelIndex = groupLabelArr.length - 1;
							if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
								groupLabelIndex = groupIdCache[mapAttr.GroupID];
							}
							groupLabelArr[groupLabelIndex].children.push({
								formItemType: 11,
								value: defaultValue,
								propName: 'TB_' + mapAttr.KeyOfEn,
								originName: mapAttr.KeyOfEn,
								idx: i,
								options: {
									...this.createOpeions(mapAttr),
									imgUrls
								}
							});
						}
						this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
						this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, defaultValue);
						continue;
					}
					// 进度条
					if (mapAttr.UIContralType == '50') {
						continue;
					}
					// 普通文本框
					if (mapAttr.UIHeight <= 40) {
						if (mapAttr.UIVisible) {
							let groupLabelIndex = groupLabelArr.length - 1;
							if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
								groupLabelIndex = groupIdCache[mapAttr.GroupID];
							}
							groupLabelArr[groupLabelIndex].children.push({
								formItemType: 1,
								value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
								propName: 'TB_' + mapAttr.KeyOfEn,
								originName: mapAttr.KeyOfEn,
								idx: i,
								options: {
									...this.createOpeions(mapAttr),
									maxlength: mapAttr.MaxLen,
									minlength: mapAttr.MinLen
								}
							});
						}
						this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
						this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, `${defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal}`);
						continue;
					}

					// 文本域
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: 2,
							value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								maxlength: mapAttr.MaxLen,
								minlength: mapAttr.MinLen
							}
						});
					}
					this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// 日期类型
				if (mapAttr.MyDataType == 6) {
					let frmDate = mapAttr.IsSupperText;
					let dateFmt = '';
					let dateParams = {
						year: false,
						month: false,
						day: false
					};
					if (frmDate == 0) {
						dateFmt = 'yyyy-MM-dd';
						dateParams = {
							year: true,
							month: true,
							day: true
						};
					} else if (frmDate == 3) {
						dateFmt = 'yyyy-MM';
						dateParams = {
							year: true,
							month: true,
							day: false
						};
					} else if (frmDate == 6) {
						dateFmt = 'MM-dd';
						dateParams = {
							year: false,
							month: true,
							day: true
						};
					}
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: 3,
							value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								dateFormat: dateFmt,
								dateParams
							}
						});
					}
					this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// 时期时间类型
				if (mapAttr.MyDataType == 7) {
					let frmDate = mapAttr.IsSupperText;
					let dateFmt = '';
					let timeFmt = '';
					let datePickerType = '';
					let formItemType = 12;
					let defaultValue = defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal;
					let dateValue = '';
					let timeValue = '';
					let dateParams = {
						year: false,
						month: false,
						day: false,
						hour: false,
						minute: false,
						second: false
					};
					if (frmDate == 1) {
						dateFmt = 'yyyy-MM-dd';
						timeFmt = 'HH:mm';
						datePickerType = 'datetime';
						dateParams = {
							year: true,
							month: true,
							day: true,
							hour: true,
							minute: true,
							second: false
						};
					} else if (frmDate == 2) {
						dateFmt = 'yyyy-MM-dd';
						timeFmt = 'HH:mm:ss';
						datePickerType = 'datetime';
						dateParams = {
							year: true,
							month: true,
							day: true,
							hour: true,
							minute: true,
							second: true
						};
					} else if (frmDate == 4) {
						timeFmt = 'HH:mm';
						formItemType = 4;
						dateParams = {
							year: false,
							month: false,
							day: false,
							hour: true,
							minute: true,
							second: false
						};
					} else if (frmDate == 5) {
						timeFmt = 'HH:mm:ss';
						formItemType = 4;
						dateParams = {
							year: false,
							month: false,
							day: false,
							hour: true,
							minute: true,
							second: true
						};
					}
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType,
							value: defaultValue,
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								dateFormat: dateFmt,
								timeFormat: timeFmt,
								datePickerType,
								dateParams
							}
						});
					}
					this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// boolen 类型.
				if (mapAttr.MyDataType == 4) {
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: 7,
							value: defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal,
							propName: 'CB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr)
							}
						});
					}
					this.rules['CB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'CB_' + mapAttr.KeyOfEn, defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal);
					continue;
				}

				// 枚举类型
				if (mapAttr.MyDataType == 2 && mapAttr.LGType == 1) {
					let selectOption = this.datasource[mapAttr.KeyOfEn] || this.datasource[mapAttr.UIBindKey];
					if (selectOption == undefined) {
						if (selectObj[mapAttr.UIBindKey]) {
							selectOption = selectObj[mapAttr.UIBindKey];
						} else {
							selectOption = [];
						}
					}
					let uiName = '';
					let formItemType = 6;
					if (mapAttr.UIContralType == 1) {
						uiName = 'DDL_' + mapAttr.KeyOfEn;
					} else if (mapAttr.UIContralType == 3) {
						uiName = 'RB_' + mapAttr.KeyOfEn;
						formItemType = 8;
					}
					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: formItemType,
							value: '' + defaultValueObj[mapAttr.KeyOfEn] || '' + mapAttr.DefVal,
							propName: uiName,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								selectOption
							}
						});
					}
					this.rules[uiName] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, uiName, '' + defaultValueObj[mapAttr.KeyOfEn] || '' + mapAttr.DefVal);
					continue;
				}

				// 数字类型
				if (mapAttr.MyDataType == 5 || mapAttr.MyDataType == 3 || mapAttr.MyDataType == 2 || mapAttr.MyDataType == 8) {
					let precision = 0;
					let attrdefVal = mapAttr.DefVal;
					if (attrdefVal != null && attrdefVal !== '' && attrdefVal.indexOf('.') >= 0) {
						precision = attrdefVal.substring(attrdefVal.indexOf('.') + 1).length;
					}

					if (mapAttr.UIVisible) {
						let groupLabelIndex = groupLabelArr.length - 1;
						if (groupIdCache.hasOwnProperty(mapAttr.GroupID)) {
							groupLabelIndex = groupIdCache[mapAttr.GroupID];
						}
						groupLabelArr[groupLabelIndex].children.push({
							formItemType: 5,
							value: ''+defaultValueObj[mapAttr.KeyOfEn] || ''+mapAttr.DefVal, 
							propName: 'TB_' + mapAttr.KeyOfEn,
							originName: mapAttr.KeyOfEn,
							idx: i,
							options: {
								...this.createOpeions(mapAttr),
								precision,
								numberMax: Math.pow(10, mapAttr.MaxLen + 1) - 1,
								numberMin: Math.pow(10, mapAttr.MinLen)
							}
						});
					}
					this.rules['TB_' + mapAttr.KeyOfEn] = [{ required: !!mapAttr.UIIsInput, message: `请输入${mapAttr.Name}`,trigger: ['change','blur'] }];
					this.$set(this.form, 'TB_' + mapAttr.KeyOfEn, `${defaultValueObj[mapAttr.KeyOfEn] || mapAttr.DefVal}`);
					continue;
				}
			}
			console.log('group', groupLabelArr);

			this.uiArray = groupLabelArr;
			// 多选处理
			for (let i = 0, len = uiArray.length; i < len; i++) {
				let uiObj = uiArray[i];
				if (extObj[uiObj.originName]) {
					let mapExt = extObj[uiObj.originName];
					switch (mapExt.ExtType) {
						case 'MultipleChoiceSmall': {
							this.getMultipleChoiceOption(mapExt).then(res => {
								console.log('multi', res);
								let options = res;
								uiObj.formItemType = 10;
								// uiObj.options.selectOption = options;
								uiObj.multiOptions = options;
								this.$set(this.uiArray, i, uiObj);
								this.$forceUpdate();
							});
							break;
						}
					}
				}
			}

			this.$nextTick(() => {
				if (extrasRules[this.flow.FK_Flow] && extrasRules[this.flow.FK_Flow].hasOwnProperty('init')) {
					extrasRules[this.flow.FK_Flow].init(this);
				}
				console.log('this.rules',this.rules)
				this.$refs.form.setRules(this.rules);
			});
		},
		getAthList(e) {
			let IsStartNode = 0;
			let no = this.flow.FK_Node.toString().substring(this.flow.FK_Node.toString().length - 2);
			if (no == '01') {
				IsStartNode = 1;
			}
			this.athInit({
				PKVal: this.flow.WorkID,
				FID: this.flow.FID,
				Ath: e.CtrlID.replace(`${e.FrmID}_`, ''),
				FK_MapData: `ND${this.flow.NodeID}`,
				FromFrm: e.FrmID,
				FK_FrmAttachment: e.CtrlID,
				WorkID: this.flow.WorkID,
				FK_Node: this.flow.FK_Node,
				FK_Flow: this.flow.FK_Flow,
				IsStartNode: IsStartNode,
				M: Math.random()
			})
				.then(res => {
					console.log(res);
					if (res && res.DBAths) {
						// this.form[e.formName] = [];
						setTimeout(() => {
							let arr = [];
							res.DBAths.forEach((e2, i2) => {
								let i = e2.FileFullName.indexOf('DataUser');
								let str = '/' + e2.FileFullName.substring(i);
								str = str.replace(/\\/g, '/');
								arr.push({
									...e2,
									name: e2.FileName,
									url: `${ServerUrl}${str}`
								});
							});
							this.form[e.formName] = arr;
						}, 0);
					}
				})
				.catch(err => {
					console.log(err);
				});
		},
		createOpeions(mapAttr) {
			return {
				tip: mapAttr.Tip,
				colSpan: (mapAttr.ColSpan + 1) * 6,
				isEnable: mapAttr.UIIsEnable,
				label: mapAttr.Name,
				isRequired: !!mapAttr.UIIsInput
			};
		},
		getMultipleChoiceOption(e) {
			return new Promise((resolve, reject) => {
				let returnArr = [];
				switch (e.DoWay) {
					case 1: {
						e.Tag1.split(';').forEach((e, i) => {
							returnArr.push({
								No: i,
								Name: '' + e
							});
						});
						resolve(returnArr);
						break;
					}
					case 2: {
						this.getEnums({
							EnumKey: e.Tag2
						})
							.then(res => {
								res.forEach(e => {
									e.No = e.IntKey;
									e.Name = e.Lab;
								});
								resolve(res);
							})
							.catch(err => {
								reject(err);
							});
						break;
					}
					case 3: {
						this.getSFTable({
							PKVal: e.Tag3
						})
							.then(res => {
								resolve(res);
							})
							.catch(err => {
								reject(err);
							});
						break;
					}
				}
			});
		},
		handleValueChange(obj) {
			try {
				this.form[obj.key] = obj.value;
				if (obj.name) {
					//下拉框、单选框
					let str = '';
					str = obj.key.replace('DDL_', '');
					str = str.replace('RB_', '');
					this.form[`TB_${str}T`] = obj.name;
				}
				if (obj.key.includes('smc_')) {
					//地区选择
					this.form['TB_smcProvinceId'] = obj.cityArr[0];
					this.form['TB_smcCityId'] = obj.cityArr[1];
					this.form['TB_smcDistrictId'] = obj.cityArr[2] || '';
					this.form[obj.key] = obj.cityArr[obj.cityArr.length - 1];
					// this.form[obj.key.replace("smc_", "")] = obj.value;
				}
				//额外规则
				if (extrasRules[this.flow.FK_Flow]) extrasRules[this.flow.FK_Flow].valueChange(this, obj);
				console.log(this.form)
			} catch (error) {
				console.log(error);
			}
		},
		validateAndSend() {
			return new Promise((resolve, reject) => {
				this.$refs.form.validate(valid => {
					console.log(valid,this.rules,this.form);
					if(valid){
						resolve(this.form)
					}else{
						reject()
					}
				});
			});
		},
		handleValidateItem(obj) {
			console.log(obj);
			return new Promise((resolve, reject) => {
				if (this.rules[obj.propName]) {
					//额外自定义校验规则
					this.rules[obj.propName].validator(null, obj.value, resolve, reject);
				} else {
					if (obj.isRequired) {
						if (obj.value) {
							resolve();
						} else {
							reject('请输入');
						}
					} else {
						resolve();
					}
				}
			});
		},
		isImg(str) {
			return imgReg.test(str);
		},
		previewImg(url) {
			uni.previewImage({
				urls: [url]
			});
		},
		uploadClick(item) {
			let self = this;
			let url = `${ServerUrl}/WF/Ath/AttachmentUploadS?FK_FrmAttachment=${item.CtrlID}&PKVal=${this.flow.WorkID}&FID=${this.flow.FID}&FK_Node=${
				this.flow.FK_Node
			}&FK_MapData=${item.FrmID}`;
			uni.chooseImage({
				success: chooseImageRes => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					console.log('tempFilePaths', tempFilePaths, chooseImageRes);
					uni.showLoading({
						mask: true,
						title: '上传中'
					});
					uni.uploadFile({
						url: url,
						filePath: tempFilePaths[0],
						name: 'file',
						formData: {
							name: '小程序文件'
						},
						success: uploadFileRes => {
							console.log(uploadFileRes.data);
							uni.hideLoading();
							self.getAthList(item);
						},
						fail() {
							uni.hideLoading();
							self.getAthList(item);
						}
					});
				}
			});
		},
		athDelClick(ath, item) {
			console.log(ath, item);
			let self = this;
			uni.showModal({
				title: '删除附件',
				content: '确定删除附件？',
				success(res) {
					if (res.confirm) {
						self.athDelete({
							DelPKVal: item.MyPK
						})
							.then(res => {
								self.getAthList(ath);
							})
							.catch(err => {
								self.getAthList(ath);
							});
					}
				}
			});
		}
	}
};
</script>

<style lang="less">
._CreateFormContainer {
	.formLabel {
		text-align: center;
	}
	.fileList {
		.athImgCon {
			display: flex;
			align-items: center;
			width: 100%;
			.athImgItem {
				padding: 20rpx;
				.athImg {
					width: 100rpx;
					height: 100rpx;
				}
			}
			.athImgName {
				flex: 1;
				font-size: 30rpx;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}
			.athImgClose {
				padding: 20rpx;
				.athImgIcon {
					font-size: 30rpx;
				}
			}
		}
	}
	.formItemCon {
		padding: 0 24rpx;
	}
}
</style>
